from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
                               QStackedWidget, QStatusBar, QSystemTrayIcon, QMenu)
from PySide6.QtCore import Signal, Qt
from PySide6.QtGui import QIcon
from .dashboard import DashboardPage
from .product import ProductPage
from .purchase import PurchasePage
from .sale import SalesPage
from .supplier import SupplierPage
from .user import UserPage
from .customer import CustomerPage
from .widgets.basewidgets import TimeLabel, CameraInitThread, NormalLabel, MenuPushButton
from common import config

class MainWindow(QMainWindow):
    LoggoutSuccess = Signal()

    def __init__(self):
        super().__init__()
        self.setWindowTitle("进销存管理系统")
        self.resize(1200, 800)
        self.setMinimumWidth(1200)
        self.setWindowIcon(QIcon("resources/icons/app_logo.png"))
        self.quit = False  #是否真正退出
        
        # 创建主布局
        main_widget = QWidget()
        main_layout = QHBoxLayout(main_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        
        # 创建左侧菜单
        self.sidebar = self.create_sidebar()
        main_layout.addWidget(self.sidebar)
        
        # 创建右侧容器
        right_container = QWidget()
        right_layout = QVBoxLayout(right_container)
        right_layout.setContentsMargins(0, 0, 0, 0)
        right_layout.setSpacing(0)
        
        # 创建右侧内容区
        self.content_area = QStackedWidget()
        self.content_area.currentChanged.connect(self.on_content_changed)
        
        # 创建各个页面
        self.dashboard_page = DashboardPage()
        self.product_page = ProductPage()
        self.purchase_page = PurchasePage()
        self.sales_page = SalesPage()
        self.supplier_page = SupplierPage()
        self.user_page = UserPage()
        self.customer_page = CustomerPage()
        
        # 添加页面到堆叠窗口
        self.content_area.addWidget(self.dashboard_page)
        self.content_area.addWidget(self.product_page)
        self.content_area.addWidget(self.purchase_page)
        self.content_area.addWidget(self.sales_page)
        self.content_area.addWidget(self.supplier_page)
        self.content_area.addWidget(self.user_page)
        self.content_area.addWidget(self.customer_page)

        # 创建状态栏
        status_bar = QStatusBar()

        # 摄像头状态
        self.camera_status_label = NormalLabel("摄像头启用中...")
        status_bar.addPermanentWidget(self.camera_status_label)
        self.start_camera_thread = CameraInitThread()
        self.start_camera_thread.result.connect(self.on_camera_initialized)
        self.start_camera_thread.start()

        # 时间
        self.time_label = TimeLabel()
        status_bar.addPermanentWidget(self.time_label)
        
        # 将内容区和状态栏添加到右侧容器
        right_layout.addWidget(self.content_area)
        right_layout.addWidget(status_bar)
        
        # 添加右侧容器到主布局
        main_layout.addWidget(right_container)
        
        # 设置左右区域的比例
        main_layout.setStretchFactor(self.sidebar, 1)
        main_layout.setStretchFactor(right_container, 8)
        
        self.setCentralWidget(main_widget)
        self.init_tray_icon()

    
    def create_sidebar(self):
        sidebar = QWidget()
        sidebar.setObjectName("sidebar")
        
        layout = QVBoxLayout(sidebar)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        
        # 顶部标题
        title_widget = QWidget()
        title_widget.setObjectName("titlePanel")
        title_layout = QVBoxLayout(title_widget)
        title_label = QLabel("进销存")
        title_label.setObjectName("titleLabel")
        title_layout.addWidget(title_label)
        layout.addWidget(title_widget)
        
        # 菜单项
        menu_items = [
            {"name": "控制台", "page_index": 0},
            {"name": "商品管理", "page_index": 1},
            {"name": "采购管理", "page_index": 2},
            {"name": "销售管理", "page_index": 3},
            {"name": "供货商管理", "page_index": 4},
            {"name": "用户管理", "page_index": 5},
            {"name": "客户管理", "page_index": 6},
        ]
        
        self.menu_buttons = []
        
        for item in menu_items:
            btn = MenuPushButton(item["name"])
            btn.page_index = item["page_index"]
            btn.clicked.connect(self.on_menu_clicked)
            layout.addWidget(btn)
            self.menu_buttons.append(btn)
        
        # 默认选中第一个菜单
        self.menu_buttons[0].setChecked(True)
        
        layout.addStretch()
        return sidebar
    
    def on_menu_clicked(self):
        sender = self.sender()
        
        # 更新按钮样式
        for btn in self.menu_buttons:
            if btn == sender:
                btn.setChecked(True)
            else:
                btn.setChecked(False)
        # 切换页面
        self.content_area.setCurrentIndex(sender.page_index)

    def on_content_changed(self):
        self.content_area.currentWidget().load_data()

    def on_camera_initialized(self, success):
        if success:
            self.camera_status_label.setText("摄像头已启用")
        else:
            self.camera_status_label.setText("摄像头启动失败，无法使用扫码功能")

    def init_tray_icon(self):
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(QIcon("resources/icons/app_logo.png"))
        
        tray_menu = QMenu()
        tray_menu.setObjectName("trayMenu")
        show_action = tray_menu.addAction("显示主窗口")
        show_action.triggered.connect(self.show_normal)

        hide_action = tray_menu.addAction("最小化")
        hide_action.triggered.connect(self.hide_to_tray)
        
        quit_action = tray_menu.addAction("退出")
        quit_action.triggered.connect(self.quit_app)
        
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.activated.connect(self.on_tray_icon_activated)
        self.tray_icon.show()

    def on_tray_icon_activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show_normal()

    def show_normal(self):
        """从托盘恢复显示"""
        self.show()
        self.activateWindow()
        self.setWindowState(Qt.WindowActive)

    def quit_app(self):
        """退出应用程序"""
        self.quit = True
        self.close()

    def hide_to_tray(self, showTip=False):
        self.hide()
        if showTip:
            self.tray_icon.showMessage("提示", "程序已最小化到系统托盘", QSystemTrayIcon.Information, 2000)

    def closeEvent(self, event):
        if self.quit:
            self.start_camera_thread.safe_stop()
            self.start_camera_thread.wait()
            super().closeEvent(event)
        else:
            event.ignore()
            self.hide_to_tray(True)

    def loggout(self):
        self.LoggoutSuccess.emit()
        self.close()

    def lock_screen(self):
        pass

